﻿using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc;
using Reader.Utils;

namespace Reader.Controllers;

public class UserController : Controller
{
    
    private readonly ApplicationDbContext _context;
    private readonly IWebHostEnvironment _hostingEnvironment;
    private readonly SessionService _sessionService;

    public UserController(ApplicationDbContext context, IWebHostEnvironment hostingEnvironment, SessionService sessionService)
    {
        _context = context;
        _hostingEnvironment = hostingEnvironment;
        _sessionService = sessionService;
    }
    
    [HttpGet]
    public IActionResult Login()
    {
        if (HttpContext.IsLogin())
            return RedirectToAction("Index", "Home");
        return View();
    }
    
    [HttpPost]
    public IActionResult Login(string username, string password)
    {
        if (HttpContext.IsLogin())
            return RedirectToAction("Index", "Home");
        var user = _context.GetUserByUsernameAndPassword(username, password);

        if (user != null)
        {
            SetLoginSession(user);
            // 身份验证成功，可以进行其他操作，比如设置用户的认证 Cookie
            return RedirectToAction("Index", "Home");
        }

        // 身份验证失败
        return View();
    }
    
    [HttpGet]
    public IActionResult Register()
    {
        if (HttpContext.IsLogin())
            return RedirectToAction("Index", "Home");
        return View();
    }
    
    [HttpPost]
    public IActionResult Register(string username, string password, string nickname)
    {
        if (HttpContext.IsLogin())
            return RedirectToAction("Index", "Home");
        // 在这里执行注册逻辑，将用户信息写入数据库或其他存储介质
        // 示例中简单将用户信息写入 Session 中
        // 判断用户名是否已存在
        if (_context.Users.Any(u => u.Username == username))
        {
            ModelState.AddModelError("Username", "用户名已存在");
        }

        // 判断手机号格式
        if (!Regex.IsMatch(username, @"^1[3456789]\d{9}$"))
        {
            ModelState.AddModelError("Username", "请输入有效的手机号格式");
        }

        // 判断密码是否为空
        if (string.IsNullOrWhiteSpace(password))
        {
            ModelState.AddModelError("Password", "密码不能为空");
        }

        // 判断昵称是否为空
        if (string.IsNullOrWhiteSpace(nickname))
        {
            ModelState.AddModelError("Nickname", "昵称不能为空");
        }

        if (ModelState.IsValid)
        {
            string fileName = $"{HashGenerator.GenerateHash(nickname)}.png";
            // 生成一个图像
            string path = Path.Combine(_hostingEnvironment.WebRootPath, "images", "avatar",
                fileName);
            if (!System.IO.File.Exists(path))
            {
                ImageGenerator.GenerateImage(nickname, path);      
            }
            var user = new User
            {
                Username = username,
                Password = password,
                Nickname = nickname,
                Role = 1,
                Avatar = $"/images/avatar/{fileName}"
            };

            _context.AddUser(user);
            // 写入Session
            SetLoginSession(user);
            // 注册完成后重定向到登录页面
            return RedirectToAction("Index", "Home");
        }
        else
        {
            return View();
        }
    }

    public IActionResult MyUpload()
    {
        if (!_sessionService.IsLogin())
        {
            return RedirectToAction("Login", "User");
        }

        int userId = _sessionService.GetInt32("user.id");
        var ret = _context.Books.Where(e => e.UploadedUserId == userId).ToList();
        ViewData["books"]= ret;
        return View();
    }


    [HttpGet]
    public IActionResult Info()
    {
        if (!_sessionService.IsLogin())
        {
            return RedirectToAction("Index", "Home");
        }
        var user = _context.Users.FirstOrDefault(e => e.UserId == _sessionService.GetUserId());
        if (user == null)
            return NotFound();
        return View(user);
    }

    [HttpPost]
    public IActionResult SaveInfo(IFormCollection form)
    {
        if (!_sessionService.IsLogin())
        {
            return NotFound();
        }
        string avatar = form["avatar"];
        string nickname = form["nickname"];
        User user = _context.Users.FirstOrDefault(e => e.UserId == _sessionService.GetUserId());
        if (user == null)
            return NotFound();
        user.Nickname = nickname;
        user.Avatar = avatar;
        _context.SaveChanges();
        return RedirectToAction("Info");
    }
    
    
    void SetLoginSession(User user)
    {
        HttpContext.Session.SetInt32("user.id", user.UserId);
        HttpContext.Session.SetString("user.username", user.Username);
        HttpContext.Session.SetString("user.nickname", user.Nickname);
        HttpContext.Session.SetInt32("user.role", user.Role);
    }
}